package com.hd.crdao.activity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.base.BaseSecondActivity;
import com.hd.crdao.bean.GetStoreAuthdataBean;
import com.hd.crdao.bean.MsgBean;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.StringUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.hd.crdao.wrapper.GlideImageUtils;
import com.hss01248.dialog.StyledDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 *
 *@author Programming
 *@date 2017/6/26 0026
 */
public class IdCertificationActivity extends BaseSecondActivity implements View.OnClickListener {
    private static final int FROM_CAMERA = 100;
    private static final int FROM_PIC = 101;
    @BindView(R.id.idcertification_head)
    ExpandHeadView mIdcertificationHead;
    @BindView(R.id.idcard_name)
    EditText mIdcardName;
    @BindView(R.id.idcard_number)
    EditText mIdcardNumber;
    @BindView(R.id.dateStart)
    TextView mDateStart;
    @BindView(R.id.dateEnd)
    TextView mDateEnd;
    @BindView(R.id.idcard_surface)
    LinearLayout mIdcardSurface;
    @BindView(R.id.idcard_back)
    LinearLayout mIdcardBack;
    @BindView(R.id.license)
    LinearLayout mLicense;
    @BindView(R.id.btnSubmit_idcert)
    Button mBtnSubmitIdcert;
    @BindView(R.id.image_surface)
    ImageView mImageSurface;
    @BindView(R.id.image_back)
    ImageView mImageBack;
    @BindView(R.id.image_license)
    ImageView mImageLicense;
    public ArrayList<String> imagePaths = new ArrayList<>();
    private int count = 0;

    private String openShopId;
    public int certstate;
    public Handler mHandler = new Handler();

    @Override
    protected void initView() {
        certstate = getIntent().getIntExtra("certstate", 0);
        if (certstate == 1) {   //审核中
            initData();
            mIdcardName.setFocusableInTouchMode(false);
            mIdcardNumber.setFocusableInTouchMode(false);
            mDateStart.setOnClickListener(null);
            mDateEnd.setOnClickListener(null);
            mImageSurface.setOnClickListener(null);
            mImageBack.setOnClickListener(null);
            mImageLicense.setOnClickListener(null);
            mBtnSubmitIdcert.setVisibility(View.GONE);
        } else if (certstate == 2) {    //不通过 显示以前填入的内容  并且可以二次提交
            initData();
            mBtnSubmitIdcert.setVisibility(View.VISIBLE);
            mDateStart.setOnClickListener(this);
            mDateEnd.setOnClickListener(this);
        } else {
            mBtnSubmitIdcert.setVisibility(View.VISIBLE);
            mDateStart.setOnClickListener(this);
            mDateEnd.setOnClickListener(this);
        }
        initEvent();
    }

    private void initData() {
        //初始化数据,将上次保存的数据提取出来
        String businessid = SPUtils.getString("businessid", "");
        OkHttpUtils.post().url(Constants.GETSTOREAUTHDATA_URL)
                .addParams("sign", Constants.SIGN)
                .addParams("carBusinessId", SPUtils.getString("businessid", ""))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("网络开了个小差");
                ALog.d(e.getMessage());

            }

            @Override
            public void onResponse(String response, int id) {
                ALog.d(response);
                GetStoreAuthdataBean getStoreAuthdataBean = new Gson().fromJson(response, GetStoreAuthdataBean.class);
                GetStoreAuthdataBean.StoreAuthdataBean storeAuthdata = getStoreAuthdataBean.getStoreAuthdata();
                if (getStoreAuthdataBean.getSuccess() == 0) {
                    mIdcardName.setText(storeAuthdata.getIdcardName());
                    mIdcardNumber.setText(storeAuthdata.getIdcardNum());
                    mDateStart.setText(StringUtils.getDate(storeAuthdata.getCreateDate()));
                    mDateEnd.setText(StringUtils.getDate(storeAuthdata.getIdcardEnddate()));
                    GlideImageUtils.loadImage(Constants.IMAGEURL + storeAuthdata.getIdcardFrontpath(),R.drawable.logo_moren_2x,mImageSurface);
                    GlideImageUtils.loadImage(Constants.IMAGEURL + storeAuthdata.getIdcardFrontback(),R.drawable.logo_moren_2x,mImageBack);
                    GlideImageUtils.loadImage(Constants.IMAGEURL + storeAuthdata.getStoreLicense(),R.drawable.logo_moren_2x,mImageLicense);
                    SPUtils.saveString("cardImage0", Constants.IMAGEURL + storeAuthdata.getIdcardFrontpath());
                    SPUtils.saveString("cardImage1", Constants.IMAGEURL + storeAuthdata.getIdcardFrontback());
                    SPUtils.saveString("cardImage2", Constants.IMAGEURL + storeAuthdata.getStoreLicense());
                    openShopId = storeAuthdata.getId();
                } else {
                    MyToast.show(getStoreAuthdataBean.getMessage());
                }
            }
        });
    }


    private void initEvent() {
        imagePaths.add(0, "");
        imagePaths.add(1, "");
        imagePaths.add(2, "");
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_idcertification;
    }

    @Override
    protected ExpandHeadView setExpandHeadView() {
        return mIdcertificationHead;
    }


    @OnClick({R.id.idcard_surface, R.id.idcard_back, R.id.license, R.id.btnSubmit_idcert})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.idcard_surface:
                count = 0;
                upLoadIdcardImage();
                break;
            case R.id.idcard_back:
                count = 1;
                upLoadIdcardImage();
                break;
            case R.id.license:
                count = 2;
                upLoadIdcardImage();
                break;
            case R.id.btnSubmit_idcert:
                final String idCardName = mIdcardName.getText().toString().trim();
                final String idCardNumber = mIdcardNumber.getText().toString().trim();
                final String dateStart = mDateStart.getText().toString().trim();
                final String dateEnd = mDateEnd.getText().toString().trim();
                StyledDialog.buildLoading().setActivity(this).show();
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (certstate == 2) {
                            changeSomeInfomations(idCardName, idCardNumber, dateStart, dateEnd);
                        } else {
                            if (checkInputInfo(idCardName, idCardNumber, dateStart, dateEnd)) {
                                upLoadSomeInfomations(idCardName, idCardNumber, dateStart, dateEnd);
                            }
                        }

                    }
                }, 2500);


                break;
        }
    }

    /**
     * 上传一些信息
     * 输  入	carBusinessId	车商ID
     * cardName	身份证名字
     * cardId	身份证号
     * idcardStartdate	证件起始日期
     * idcardEnddate	证件终止日期
     * imageNames	图片名称数组
     * images	图片流数组
     * sign	签名
     *
     * @param idCardName
     * @param idCardNumber
     * @param dateStart
     * @param dateEnd
     */
    private void upLoadSomeInfomations(final String idCardName, final String idCardNumber, final String dateStart, final String dateEnd) {
        HashMap<String, String> map = new HashMap<>();
        map.put("sign", Constants.SIGN);
        map.put("carBusinessId", SPUtils.getString("businessid", ""));
        map.put("cardName", idCardName);
        map.put("cardId", idCardNumber);
        map.put("idcardStartdate", dateStart);
        map.put("idcardEnddate", dateEnd);
        map.put("imageNames", "身份证正面,身份证反面,营业执照");
        OkHttpUtils.post().url(Constants.SHOPCERTIFICATION_URL).params(map)
                .addFile("images", imagePaths.get(0), new File(imagePaths.get(0)))
                .addFile("images", imagePaths.get(1), new File(imagePaths.get(1)))
                .addFile("images", imagePaths.get(2), new File(imagePaths.get(2)))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("网络开了个小差");
                StyledDialog.dismissLoading();
            }

            @Override
            public void onResponse(String response, int id) {
                MsgBean msgBean = new Gson().fromJson(response, MsgBean.class);
                if (msgBean.getSuccess() == 0) {
                    MyToast.show(msgBean.getMessage());
                    SPUtils.saveString("cardName", idCardName);
                    SPUtils.saveString("cardId", idCardNumber);
                    SPUtils.saveString("idcardStartdate", dateStart);
                    SPUtils.saveString("idcardEnddate", dateEnd);
                    SPUtils.saveString("cardImage0", imagePaths.get(0));
                    SPUtils.saveString("cardImage1", imagePaths.get(1));
                    SPUtils.saveString("cardImage2", imagePaths.get(2));
                    startActivity(new Intent(UIUtils.getContext(), OpenShopCertificationActivity.class));
                    finish();
                } else {
                    MyToast.show(msgBean.getMessage());
                }
                StyledDialog.dismissLoading();
            }
        });

    }

    /**
     * 检查信息是否填写完整
     *
     * @param idCardName
     * @param idCardNumber
     * @param dateStart
     * @param dateEnd
     */
    private boolean checkInputInfo(String idCardName, String idCardNumber, String dateStart, String dateEnd) {

        ALog.d(dateStart.compareTo(dateEnd) + "");
        if (TextUtils.isEmpty(idCardName)) {
            MyToast.show("请输入真实姓名");
            return false;
        } else if (TextUtils.isEmpty(idCardNumber)) {
            MyToast.show("请输入身份证号码");
            return false;
        } else if (TextUtils.isEmpty(dateStart)) {
            MyToast.show("请输入证件日期");
            return false;
        } else if (TextUtils.isEmpty(dateEnd)) {
            MyToast.show("请输入证件日期");
            return false;
        } else if (dateStart.compareTo(dateEnd) >= 0) {
            MyToast.show("结束日期要大于起始日期");
            return false;
        } else if (TextUtils.isEmpty(imagePaths.get(0))) {
            MyToast.show("请上传证件正面照");
            return false;
        } else if (TextUtils.isEmpty(imagePaths.get(1))) {
            MyToast.show("请上传证件反面照");
            return false;
        } else if (TextUtils.isEmpty(imagePaths.get(2))) {
            MyToast.show("请上传营业执照");
            return false;
        }
        //执行上传信息和照片的操作

        return true;
    }

    /**
     * 上传证件照片
     */
    private void upLoadIdcardImage() {
        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.camera_pop_menu, null);

        Button btnCamera = (Button) popView.findViewById(R.id.btn_camera_pop_camera);
        Button btnAlbum = (Button) popView.findViewById(R.id.btn_camera_pop_album);
        Button btnCancel = (Button) popView.findViewById(R.id.btn_camera_pop_cancel);
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;
        final PopupWindow popWindow = new PopupWindow(popView, width, height);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

        btnCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开系统照相机
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                startActivityForResult(intent, FROM_CAMERA);
                popWindow.dismiss();
            }
        });
        btnAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //从系统相册中获取照片
                Intent intent;
                if (Build.VERSION.SDK_INT < 19) {
                    intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                } else {
                    intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                }
                startActivityForResult(intent, FROM_PIC);
                popWindow.dismiss();
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
    }

    /**
     * 隐藏软键盘
     */
    private void hideSoftKey() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
        }
    }

    /**
     * 返回结果中拿到图片路径并赋值
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == FROM_CAMERA && resultCode == RESULT_OK) {
            if (data != null && data.getExtras() != null) {
                Bitmap bitmap = (Bitmap) data.getExtras().get("data");
                File file = new File(Environment.getExternalStorageDirectory() + "/myImage/");
                file.mkdirs();
                String fileName = Environment.getExternalStorageDirectory() + "/myImage/" + System.currentTimeMillis() + ".jpg";
                try {
                    FileOutputStream b = new FileOutputStream(fileName);
                    assert bitmap != null;
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);
                    b.flush();
                    b.close();
                    ALog.d("照片已保存到：" + fileName);
                    if (count == 0) {
                        GlideImageUtils.loadImage(fileName,R.drawable.idcard_2x,mImageSurface);
                    } else if (count == 1) {
                       GlideImageUtils.loadImage(fileName,R.drawable.idcardb_2x,mImageBack);
                    } else {
                        GlideImageUtils.loadImage(fileName,R.drawable.license,mImageLicense);
                    }
                    imagePaths.set(count, fileName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        //从图库选择返回的结果
        if (requestCode == FROM_PIC && resultCode == RESULT_OK) {

            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String imagePath = cursor.getString(columnIndex);
                if (count == 0) {
                    GlideImageUtils.loadImage(imagePath,R.drawable.logo_moren_2x,mImageSurface);
                } else if (count == 1) {
                    GlideImageUtils.loadImage(imagePath,R.drawable.logo_moren_2x,mImageBack);
                } else {
                    GlideImageUtils.loadImage(imagePath,R.drawable.logo_moren_2x,mImageLicense);
                }

                ALog.d(imagePath);
                imagePaths.set(count, imagePath);
                cursor.close();
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.dateStart:
                hideSoftKey();
                timeSelected("起始有效期", mDateStart);
                break;
            case R.id.dateEnd:
                hideSoftKey();
                timeSelected("结束有效期", mDateEnd);
                break;
        }

    }


    /**
     * 时间选择器
     *
     * @param title
     * @param textView
     */

    private void timeSelected(String title, final TextView textView) {
        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE);
                textView.setText(String.valueOf(format.format(date)));
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false,})//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确认")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText(title)//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.parseColor("#2e2e2e"))//标题文字颜色
                .setSubmitColor(Color.parseColor("#2e2e2e"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#2e2e2e"))//取消按钮文字颜色
                .setTitleBgColor(0x000000)//标题背景颜色 Night mode
                .setBgColor(0x000000)//滚轮背景颜色 Night mode
                .setDate(Calendar.getInstance())// 默认是系统时间*/
                .setLabel("年", "月", "日", null, null, null)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build();
        pvTime.show();

    }


    private void changeSomeInfomations(final String idCardName, final String idCardNumber, final String dateStart, final String dateEnd) {
        HashMap<String, String> map = new HashMap<>();
        map.put("id", openShopId);
        for (int i = 0; i < imagePaths.size(); i++) {
            if (TextUtils.isEmpty(imagePaths.get(i))) {
                imagePaths.set(i, SPUtils.getString("cardImage" + i, ""));
            }
        }
        map.put("sign", Constants.SIGN);
        map.put("carBusinessId", SPUtils.getString("businessid", ""));
        map.put("cardName", idCardName);
        map.put("cardId", idCardNumber);
        map.put("idcardStartdate", dateStart);
        map.put("idcardEnddate", dateEnd);


        PostFormBuilder builder = OkHttpUtils.post().url(Constants.UPDATESHOPCERTIFICATION_URL).params(map);
        String[] images = new String[]{"idcardFrontpath", "idcardFrontback", "storeLicense"};
        for (int i = 0; i < imagePaths.size(); i++) {
            String imagepath = imagePaths.get(i);
            if (!imagepath.contains(Constants.IMAGEURL)) {
                builder.addFile(images[i], imagePaths.get(i), new File(imagePaths.get(i)));
            }
        }
        /*if (!TextUtils.isEmpty(imagePaths.get(0))) {
            builder.addFile("idcardFrontpath", imagePaths.get(0), new File(imagePaths.get(0)));
        } else if (!TextUtils.isEmpty(imagePaths.get(1))) {
            builder.addFile("idcardFrontback", imagePaths.get(1), new File(imagePaths.get(1)));
        } else {
            builder.addFile("storeLicense", imagePaths.get(2), new File(imagePaths.get(2)));
        }*/


        builder.build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("网络开了个小差");
                StyledDialog.dismissLoading();
            }

            @Override
            public void onResponse(String response, int id) {
                MsgBean msgBean = new Gson().fromJson(response, MsgBean.class);
                if (msgBean.getSuccess() == 0) {
                    MyToast.show(msgBean.getMessage());
                    SPUtils.saveString("cardName", idCardName);
                    SPUtils.saveString("cardId", idCardNumber);
                    SPUtils.saveString("idcardStartdate", dateStart);
                    SPUtils.saveString("idcardEnddate", dateEnd);
                    SPUtils.saveString("cardImage0", imagePaths.get(0));
                    SPUtils.saveString("cardImage1", imagePaths.get(1));
                    SPUtils.saveString("cardImage2", imagePaths.get(2));
                    startActivity(new Intent(UIUtils.getContext(), OpenShopCertificationActivity.class));
                    finish();
                } else {
                    MyToast.show(msgBean.getMessage());
                }
                StyledDialog.dismissLoading();
                ALog.d(response);
            }
        });

    }

}
